<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
      @search="onSearch(keyword)"
    >
      <template #action>
        <div @click="onSearch(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="keyword">
      <van-cell
        v-for="item in lianxiang"
        :key="item"
        icon="search"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, keyword)"></span
      ></van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        v-for="item in localsearch"
        :key="item"
        :title="item"
        @click="onSearch(item)"
      >
        <van-icon name="close" @click.stop="delhostl(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { lianxiangci } from '@/api/search'
import { setLocalSearch, getlocalsearch } from '@/utils/localhost'

export default {
  name: 'Search',
  data() {
    return {
      falg: true,
      keyword: '',
      lianxiang: {},
      localsearch: getlocalsearch()
    }
  },
  methods: {
    onSearch(keyword) {
      this.localsearch = this.localsearch.filter(item => item !== keyword)
      this.localsearch.unshift(keyword)
      setLocalSearch(this.localsearch)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },

    // 输入联想词语
    inputFn() {
      clearTimeout(this.timeid)
      this.timeid = setTimeout(async () => {
        try {
          if (!this.keyword) {
            return
          }

          const res = await lianxiangci(this.keyword)
          this.lianxiang = res.data.options
        } catch {}
      }, 1000)
    },

    // 过滤红色高亮
    highLight(str, keyword) {
      if (str) {
        return str.replace(
          new RegExp(keyword, 'gi'),
          item => `<span style="color: red">${item}</span>`
        )
      } else {
      }
    },
    // 删除某条历史搜索记录
    delhostl(str) {
      const list = getlocalsearch().filter(item => item !== str)
      setLocalSearch(list)
      this.localsearch = list
    }
  },
  computed: {}
}
</script>

<style></style>
